import { MyDB, DB } from '../../share/share'

let making = Promise.resolve()
let imgList: string[] = []
let contentList: string[] = []

// debug用 ↓
Object.defineProperty(window, 'DB', {value: DB})

/** 获取图片 */
async function getImg (msg: string[], port: any) {
  let name = msg[0]
  let url = msg[1]
  let IMGRes = await fetch(url)
  let IMGMime = await (() => {
    let ContenType = IMGRes.headers.get('Content-Type').match(/\/(\w+)/)
    return ContenType === null ? 'jpeg' : ContenType[1]
  })()
  let IMGType = await (() => {
    let mime2suf = new Map([
      ['jpeg', 'jpg'],
      ['bmp', 'bmp'],
      ['webp', 'webp'],
      ['gif', 'gif'],
      ['png', 'png']
    ])
    let suf = mime2suf.get(IMGMime) || 'jpg'
    port.postMessage([name, suf])// 很重要
    return suf
  })()
  let IMGSource = await IMGRes.blob()
  let id = await DB.allIMG.add({source: IMGSource, name: name, mime: IMGMime, ext: IMGType})
  // write test
  // let nameCollect = await DB.allIMG.where('name').equals(name)
  // nameCollect.each( (item) => {
  //   console.log(`img name is ${item.name} and its size is ${item.source.size}`)
  // })
}
/** 处理文字 */
async function saveContent (sectL: string[]) {
  try {
    let name = sectL[0]
    let section = sectL[1]
    await DB.allText.add({source: section, title: '', path: name})
    // write test
    // let nameCollect = await DB.allText.where('path').equals(name)
    // nameCollect.each( (item) => {
    //   console.log(`this section name is ${item.path} and its first 10 words are ${item.source.substr(0, 10)}`)
    // })
  } catch (err) {
    console.log(err)
  }
}

// 通讯处理
browser.runtime.onConnect.addListener(function (port: any) {
  if ( port.name === 'fetch') {
    port.onMessage.addListener(async (msg: Array<string>) => {
      making.then(async () => {
        window.ProcessingTabPort.postMessage({type: 'fetch', name: msg[0]})
        console.log(`'fetch', name: ${msg[0]}`)
        await getImg(msg, port)
      })
    })
  } else if (port.name === 'storage') {
    port.onMessage.addListener(async (msg: string[]) => {
      making.then(async () => {
        window.ProcessingTabPort.postMessage({type: 'storage', name: msg[0]})
        console.log(`'storage', name: ${msg[0]}`)
        await saveContent(msg)
      })
    })
  } else if (port.name === 'fontEnd ready') {
    console.log('清除数据库ing')
    DB.renew() // 注意此处需要放置在按钮响应中
    console.log('清除完毕')
  } else if (port.name === 'allDone') {
    making.then(() => {
      // 有个问题很难解决啊……不按顺序触发，游客嗯那个造成渲染失败
      browser.tabs.connect(
        window.ActiveTabs,
        {name: 'BGAllDone'}
      )
    })
  } else if (port.name === 'test') {
    port.onMessage.addListener(function (msg: JSON | string) {
      browser.tabs.query(
        {active: true, currentWindow: true},
        function (Tabs) {
          const port = browser.tabs.connect(
            Tabs[0].id,
            {name: 'progress'}
          )
          if (window.hasOwnProperty('ProcessingTabPort')) window.ProcessingTabPort = port
          else Object.defineProperty(window, 'ProcessingTabPort', {value: port, writable: true})
          if (window.hasOwnProperty('ActiveTabs')) window.ActiveTabs = Tabs[0].id
          else Object.defineProperty(window, 'ActiveTabs', {value: Tabs[0].id, writable: true})
        }
      )
      console.log(msg)
    })
  } else if (port.name === 'debug') {
    port.onMessage.addListener(function (msg: string) {
      if (typeof msg !== 'string') {
        let errorPort = browser.runtime.connect({name: 'error'})
        errorPort.postMessage('msg is not an string as requirement')
      } else {
        let debugPort = browser.runtime.connect({name: 'debug'})
        debugPort.postMessage(msg)
      }
    })
  } else {
    console.log('error:未知参数！port.name:' + port.name)
  }
})
